import { existsSync, readFileSync, writeFile } from 'fs'
import { join } from 'path'
import { SessionItem } from '.';
import { MD5 } from './utils';

const session_save_path = join(__dirname, '../.session');
let token_map_session: {
    [token: string]: SessionItem
} = {};
export const session_map_token: {[session: string]: string} = {};
if (existsSync(session_save_path)) {
    try {
        token_map_session = JSON.parse(readFileSync(session_save_path).toString());
        Object.keys(token_map_session).map(token => {
            const { session } = token_map_session[token]
            session_map_token[session] = token
        })
    } catch (e) {
        console.error(e)
    }
}

export const createSession = ({
    token = '',
    expire = 0,
    ip = ''
}, onSessionChange?: (token_map_session: { [k: string]: string }, session_path?: string) => void) => {
    const session = MD5(token + Date.now());
    const old_session = token_map_session[token]
    if (old_session) {
        delete session_map_token[old_session.session]
    }
    
    token_map_session[token] = {
        session, expire, ip
    };

    session_map_token[session] = token
    writeFile(session_save_path, JSON.stringify(token_map_session), function (e) { e && console.error(e); });
    onSessionChange && onSessionChange(session_map_token)
    return session;
}

export const getSession = (token: string) => {
    const session = token_map_session[token]
    if (session && session.expire > Date.now()) {
        return session
    } else {
        return null
    }
}
export const getToken = (session_id: string) => {
    return session_map_token[session_id]
}